package cn.youdian.web.admin.shiro;

import cn.youdian.data.entity.User;
import cn.youdian.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Shiro授权
 *
 * @author K.J
 * @date 2021.05.31 00:11:55
 */
public class AuthorizerRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权方法(权限处理)
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        UserProfile principal = (UserProfile) principalCollection.getPrimaryPrincipal();
//
//        // 硬编码（赋予用户权限或角色）
//        if(principal.getUserName().equals("MarkerHub")){
//            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//            info.addRole("admin");
//            return info;
//        }
        return null;
    }

    /**
     * 认证方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.login(token.getUsername(), String.valueOf(token.getPassword()));
        if(user!=null) {
            UserProfile profile = new UserProfile();
            profile.setUserName(user.getUserName());
            // 把用户信息存到session中，方便前端展示
            SecurityUtils.getSubject().getSession().setAttribute("profile", profile);

            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(profile, token.getCredentials(), getName());
            return info;
        }

        throw new IncorrectCredentialsException();
    }
}
